import 'package:flutter/material.dart';
import 'package:flutter_study/routes/widget/inherited/inherited_provider.dart';

class ChangeNotifierProvider<T extends ChangeNotifier> extends StatefulWidget {
  final Widget child;
  final T data;

  ChangeNotifierProvider({required this.child, required this.data});

  static T of<T>(BuildContext context, {bool listen = true}) {
    /// 绑定子组件与 InheritedWidget 的依赖关系, 并且返回 InheritedWidget 中的 model
    final provider = listen ? context.dependOnInheritedWidgetOfExactType<InheritedProvider>() :
    context.getElementForInheritedWidgetOfExactType<InheritedProvider>()?.widget
    as InheritedProvider<T>;
    return provider?.data;
  }

  @override
  State<StatefulWidget> createState() {
    return ChangeNotifierProviderState();
  }

}

class ChangeNotifierProviderState<T extends ChangeNotifier>
    extends State<ChangeNotifierProvider<T>> {

  /// 如果数据发生变化（model类调用了notifyListeners），重新构建InheritedProvider
  void update() {
    setState(() {

    });
  }

  @override
  void didUpdateWidget(covariant ChangeNotifierProvider<T> oldWidget) {
    /// 当 Provider 更新时，如果新旧数据不"=="，则解绑旧数据监听，同时添加新数据监听
    if(widget.data != oldWidget.data) {
      oldWidget.data.removeListener(update);
      widget.data.addListener(update);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    ///  给 model 添加监听器
    widget.data.addListener(update);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    /// model 数据改变，会重新构建 InheritedProvider
    return InheritedProvider<T>(data: widget.data, child: widget.child);
  }

  @override
  void dispose() {
    // 移除model的监听器
    widget.data.removeListener(update);
    super.dispose();
  }

}